/**
 * Filename: YNBannerWebActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/18 1:03
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.umeng.analytics.MobclickAgent;

public class TimeGoodsWebActivity extends BaseActivity {
    private WebView banner_webView;
    private ProgressDialog mProgressDialog;
    private LinearLayout lltg_web;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (inCustomView()) {
                hideCustomView();
                return true;
            } else {
                finish();
            }
        }
        return false;
    }

    public boolean inCustomView() {
        return (myView != null);
    }

    public void hideCustomView() {
        videoClient.onHideCustomView();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        setContentView(R.layout.yn_find_timegood_web);
        initView();
    }

    private void initView() {
        lltg_web = (LinearLayout) findViewById(R.id.lltg_web);
        banner_webView = (WebView) findViewById(R.id.banner_webView);
        banner_webView.setDrawingCacheEnabled(true);
        banner_webView.getSettings().setDefaultTextEncodingName("utf-8");
        banner_webView.getSettings().setJavaScriptEnabled(true);
//        banner_webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        // banner_webView.getSettings().setPluginsEnabled(true);//可以使用插件
//        banner_webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//        banner_webView.getSettings().setAllowFileAccess(true);
//        banner_webView.getSettings().setLoadWithOverviewMode(true);
//        banner_webView.getSettings().setUseWideViewPort(true);
//        banner_webView.setVisibility(View.VISIBLE);
        banner_webView.addJavascriptInterface(new WebAppInterface(), "Android");
        String url = null;
        if (getIntent() != null && getIntent().getStringExtra("url") != null) {
            url = getIntent().getStringExtra("url");
            if (url.contains("?") && url.split("[?]")[0].endsWith("playaudio")) {
                url = url + "&from=yinian";
            }
            banner_webView.loadUrl(url);
        } else {
            String tarUrl = getResources().getString(R.string.TIMEGOODURL) + application.getCurID();
            //  String tarUrl = "http://wx.zhuiyinanian.com/vadio/?vadio=8dba93db-9771-4ec4-bb07-38299d808168.mp4";
            banner_webView.loadUrl(tarUrl);
        }
        banner_webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//                super.onReceivedError(view, request, error);
                Toast.makeText(TimeGoodsWebActivity.this, "网页错误！", Toast.LENGTH_LONG).show();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
        banner_webView.setWebChromeClient(videoClient);

//        BaseWebChromeClient mWebChromeClient = new BaseWebChromeClient();
//        mWebChromeClient.init(banner_webView, banner_webView, (ViewGroup) banner_webView.getParent(),
//                new BaseWebChromeClient.Callback() {
//
//                    @Override
//                    public void enterFullscreenVideo() {
//                        WindowManager.LayoutParams attrs = getWindow().getAttributes();
//                        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
//                        attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//                        getWindow().setAttributes(attrs);
//                        if (android.os.Build.VERSION.SDK_INT >= 14) {
//                            // noinspection all
//                            getWindow().getDecorView().setSystemUiVisibility(
//                                    View.SYSTEM_UI_FLAG_LOW_PROFILE);
//                        }
//
//                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                    }
//
//                    @Override
//                    public void exitFullscreenVideo() {
//                        WindowManager.LayoutParams attrs = getWindow().getAttributes();
//                        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
//                        attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//                        getWindow().setAttributes(attrs);
//                        if (android.os.Build.VERSION.SDK_INT >= 14) {
//                            // noinspection all
//                            getWindow().getDecorView().setSystemUiVisibility(
//                                    View.SYSTEM_UI_FLAG_VISIBLE);
//                        }
//
//                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                    }
//
//                });
    }

    private View myView = null;
    private WebChromeClient.CustomViewCallback myCallback = null;

    WebChromeClient videoClient = new WebChromeClient() {
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            lltg_web.setBackgroundColor(getResources().getColor(R.color.black));
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            if (myCallback != null) {
                myCallback.onCustomViewHidden();
                myCallback = null;
                return;
            }
            long id = Thread.currentThread().getId();

            ViewGroup parent = (ViewGroup) banner_webView.getParent();
            String s = parent.getClass().getName();
            parent.removeView(banner_webView);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            parent.addView(view);
            myView = view;
            myCallback = callback;
            videoClient = this;
        }

        @Override
        public void onHideCustomView() {
            lltg_web.setBackgroundColor(getResources().getColor(R.color.black));
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            long id = Thread.currentThread().getId();
            if (myView != null) {
                if (myCallback != null) {
                    myCallback.onCustomViewHidden();
                    myCallback = null;
                }
                ViewGroup parent = (ViewGroup) myView.getParent();
                parent.removeView(myView);
                parent.addView(banner_webView);
                myView = null;
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                mProgressDialog.dismiss();
            } else {
                mProgressDialog.show();
            }
        }
    };


    public class WebAppInterface {

        @JavascriptInterface
        public void doFinish() {
            finish();
        }

        @JavascriptInterface
        public void doCustom(String type) {
            switch (Integer.parseInt(type)) {
                case 1:
                    MainActivity.goodsid = 1;
                    startActivity(new Intent(TimeGoodsWebActivity.this, TimeGoodsAlbumActivity.class));
                    finish();
                    break;
                case 2:
                    MainActivity.goodsid = 2;
                    startActivity(new Intent(TimeGoodsWebActivity.this, TimeGoodsAlbumActivity.class));
                    finish();
                    break;
                case 3:
                    MainActivity.goodsid = 3;
                    startActivity(new Intent(TimeGoodsWebActivity.this, TimeGoodsAlbumActivity.class));
                    finish();
                    break;
                case 4:
                    MainActivity.goodsid = 4;
                    startActivity(new Intent(TimeGoodsWebActivity.this, TimeGoodsAlbumActivity.class));
                    finish();
                    break;
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        banner_webView.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        banner_webView.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

}
